import router from './router'
import store from './store'
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
// import ca from "element-ui/src/locale/lang/ca";


const whiteList = ['/login'] // no redirect whitelist
router.beforeEach(async(to, from, next) => {
    document.title = getPageTitle(to.meta.title)
    // determine whether the user has logged in
    if (getToken()) {
        if (to.path === '/login') {
            next();
        } else {
            const hasRoles = store.getters.roles && store.getters.roles.length > 0
            if (hasRoles) {
                next();
            } else {
                try {
                    store.dispatch('user/getInfo').then(() =>{
                        store.dispatch('GenerateRoutes' ).then(accessRoutes =>{
                            router.addRoutes(accessRoutes)
                            router.options.routes = router.options.routes.concat(accessRoutes)//第三步
                            next({ ...to, replace: true })
                        })
                    })
                }catch (error) {
                    // remove token and go to login page to re-login
                    await store.dispatch('user/resetToken')
                    next(`/login?redirect=${to.path}`)
                }
            }
        }
    } else {
        /* has no token*/
        if (whiteList.indexOf(to.path) !== -1) {
            // in the free login whitelist, go directly
            next()
        } else {
            // other pages that do not have permission to access are redirected to the login page.
            next(`/login?redirect=${to.path}`)
            // NProgress.done()
        }
    }
})
//
// router.afterEach(() => {
//     // finish progress bar
//     NProgress.done()
// })
